package com.app.shortvideo.net.base

import com.app.shortvideo.BuildConfig
import com.app.shortvideo.config.Constant
import com.app.shortvideo.Session
import com.app.library.utils.openId.OpenUDID_manager
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.Utils
import com.chuckerteam.chucker.api.ChuckerInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

object BuildAPI {

    private var headerRetrofit: Retrofit? = null

    /**
     * 添加自定义header
     *
     * @return 自定义的OkHttpClient
     */
    private val tokenClient: OkHttpClient
        get() {
            val builder = OkHttpClient.Builder()
            if (BuildConfig.LOG_DEBUG) {
                builder.addInterceptor(ChuckerInterceptor(Utils.getApp()))
            }
            builder.proxy(Proxy.NO_PROXY)
            return builder.addInterceptor { chain ->
                val request = chain.request()
                    .newBuilder()
//                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json;charset=UTF-8")
                    .addHeader("Accept-Encoding", "identity")
                    .addHeader(Constant.PLATFORM, "1")
                    .addHeader(Constant.DEVICE_ID, OpenUDID_manager.getOpenUDID())
                    .addHeader(Constant.VERSION, AppUtils.getAppVersionName())
                if (Session.isSessionOpen()) {
                    request.addHeader("Authorization", Session.getToken())
                }
                chain.proceed(request.build())
            }
                .addNetworkInterceptor(HttpLogInterceptor("Log", BuildConfig.DEBUG))
//                .addNetworkInterceptor(SignatureInterceptor())
//                .addNetworkInterceptor(StethoInterceptor())
//                .addInterceptor(TokenInterceptor())
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build()
        }

    /**
     * 构造有自定义header字段token的Retrofit
     *
     * @return APIServers
     */
    fun <T> buildAPISevers(service: Class<T>): T {
        if (headerRetrofit == null) {
            headerRetrofit = Retrofit.Builder().baseUrl(Constant.getServer())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(tokenClient)
                .build()
        }
        return headerRetrofit!!.create(service)
    }

    fun clear() {
        headerRetrofit = null
    }

}
